package com.huawei.studentms.servlet;

import com.google.gson.Gson;
import com.huawei.studentms.base.BaseRes;
import com.huawei.studentms.entity.StudentEntity;
import com.huawei.studentms.service.StudentService;
import com.huawei.studentms.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 黄后林
 * @date 2022-11-06 10:33:43
 * @note 程序员是用代码喂出来的
 */

// http://localhost:8083/find/all
@WebServlet("/find/all")
public class SelectAllStudentServlet extends HttpServlet {


    private StudentService service = new StudentServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {

        BaseRes res;
        try {
            List<StudentEntity> list = service.findAll();
            res = BaseRes.getSuccess(list);

        } catch (Exception e) {
            res =BaseRes.getFailure();
            System.out.println("log..." + e);
            e.printStackTrace();
        }

        //2、把数据转化为JSON格式的字符串
        Gson gson =new Gson();
        String jsonData = gson.toJson(res);

        //3、设置编码格式
        response.setContentType("text/json;charset=utf-8");

        //4、把结果用流的方式给到前端
        PrintWriter writer=response.getWriter();
        writer.write(jsonData);
    }
}
